package by.gravity.helper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import by.gravity.constants.DBConstants;

public final class ConnectionHelper implements DBConstants {

	private static ConnectionHelper instance;

	private Connection connection;

	private boolean driverInited = false;

	public static final ConnectionHelper getInstance() {
		if (instance == null) {
			instance = new ConnectionHelper();
		}

		return instance;
	}

	private ConnectionHelper() {

	}

	private Connection openConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		if (!driverInited) {
			initDbDriver();
		}
		if (connection == null) {
			connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		}
		return connection;

	}

	private Statement getStatement() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		return openConnection().createStatement();

	}

	public ResultSet executeQuery(String query) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		return getStatement().executeQuery(query);
	}

	private void initDbDriver() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		Class.forName("org.gjt.mm.mysql.Driver").newInstance();
		driverInited = true;
	}
}
